#!/bin/bash

# Nginx Configuration Manager Startup Script

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PYTHON_SCRIPT="$SCRIPT_DIR/nginx_config_manager.py"
REQUIREMENTS_FILE="$SCRIPT_DIR/requirements.txt"

echo "=== Nginx Configuration Manager Startup ==="

# Check if running as root
if [[ $EUID -ne 0 ]]; then
   echo "Warning: This script is not running as root."
   echo "Some operations may fail. Consider running with sudo."
   echo ""
fi

# Check if Python script exists
if [[ ! -f "$PYTHON_SCRIPT" ]]; then
    echo "Error: Python script 'nginx_config_manager.py' not found in $SCRIPT_DIR"
    exit 1
fi

# Check if Python 3 is installed
if ! command -v python3 &> /dev/null; then
    echo "Error: Python 3 is not installed or not in PATH"
    exit 1
fi

# Check if pip is installed
if ! command -v pip3 &> /dev/null; then
    echo "Error: pip3 is not installed or not in PATH"
    echo "Please install pip3 to continue"
    exit 1
fi

# Install requirements if they exist
if [[ -f "$REQUIREMENTS_FILE" ]]; then
    echo "Installing Python dependencies..."
    pip3 install -r "$REQUIREMENTS_FILE"
    echo "Dependencies installed successfully."
    echo ""
else
    echo "Warning: requirements.txt not found. Installing Flask manually..."
    pip3 install Flask
fi

# Check nginx installation
if ! command -v nginx &> /dev/null; then
    echo "Warning: nginx is not installed or not in PATH"
    echo "The script will run but nginx operations will fail."
    echo ""
fi

# Check systemctl availability
if ! command -v systemctl &> /dev/null; then
    echo "Warning: systemctl is not available"
    echo "Nginx reload operations may fail."
    echo ""
fi

echo "Starting Nginx Configuration Manager..."
echo "Python script: $PYTHON_SCRIPT"
echo "Server will run on: http://0.0.0.0:5000"
echo ""
echo "Available endpoints:"
echo "  POST /update-config - Update nginx configuration"
echo "  GET /health - Health check"
echo "  GET / - Usage information"
echo ""
echo "Press Ctrl+C to stop the server"
echo "=========================="

# Change to script directory
cd "$SCRIPT_DIR"

# Start the Python script
exec python3 "$PYTHON_SCRIPT"
